package entity

import (
	"fmt"
	"time"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

//ShIndiPhjr 个贷普惠导入
type ShIndiPhjr struct {
	ID   int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	JJH  string    `gorm:"column:JJH"`
	KHMC string    `gorm:"column:KHMC"`
	DRRQ time.Time `gorm:"column:DRRQ"`
	ACID int       `gorm:"column:ACID"`
}

//TableName
func (ShIndiPhjr) TableName() string {
	return "SH_INDI_PHJR"
}

// BeforeCreate
func (u *ShIndiPhjr) BeforeCreate(tx *gorm.DB) (err error) {
	err = base.CHDB.Raw("SELECT ID FROM T_INDI_LOAN WHERE EVNO=? AND CUNM=?", u.JJH, u.KHMC).Row().Scan(&u.ACID)
	if err != nil {
		err = fmt.Errorf("借据编号%s或客户名称%s在系统中不存在！", u.JJH, u.KHMC)
		return
	}
	//判断是否重复导入
	var count int
	if u.ID == 0 {
		tx.Raw(`SELECT COUNT(*) FROM "SH_INDI_PHJR" WHERE "ACID"=? AND "DRRQ"=?`, u.ACID, u.DRRQ).Row().Scan(&count)
		if count > 0 {
			err = fmt.Errorf("客户名称:%s,不能重复导入！", u.KHMC)
			return
		}
	}
	return
}

// AfterCreate
func (u *ShIndiPhjr) AfterCreate(tx *gorm.DB) (err error) {
	var (
		count          int
		sqlStr         string
		monthStartTime *time.Time
	)
	tx.Raw(`SELECT COUNT(*) FROM "SH_INDI_PHJR_ZIPPER" WHERE "ACID"=? AND "EDATE"='2099-12-31'`, u.ACID).Row().Scan(&count)
	if count == 0 {
		monthStartTime = base.GetFirstDateOfMonth(&u.DRRQ)
		sqlStr = `INSERT INTO "SH_INDI_PHJR_ZIPPER"("ACID", "SDATE", "EDATE", "ISPH") VALUES(?, ?, '2099-12-31', 1)`
		err = tx.Exec(sqlStr, u.ACID, monthStartTime).Error
		if err != nil {
			return err
		}
	}
	return
}

func ShIndiPhjrAfterImport(tx *gorm.DB, params map[string]string) (err error) {
	prams := params["DRRQ"]
	dtid, _ := time.Parse("2006-01-02", prams[:10])
	dtid = dtid.AddDate(0, -1, 0)
	monthEndTime := base.GetLastDateOfMonth(&dtid)
	var sqlStr string
	if base.AppConf.Database.Mysql != "" {
		sqlStr = `UPDATE "SH_INDI_PHJR_ZIPPER" A LEFT JOIN "SH_INDI_PHJR" B ON A."ACID"=B."ACID" SET A."EDATE"=?
		WHERE B."ACID" IS NULL AND A."EDATE"='2099-12-31' AND B."DRRQ"=?`
	} else {
		sqlStr = `UPDATE "SH_INDI_PHJR_ZIPPER" SET "EDATE"=? 
		WHERE "EDATE"='2099-12-31' and not exists (select 0 from "SH_INDI_PHJR" where "DRRQ"=? and "ACID"="SH_INDI_PHJR_ZIPPER"."ACID")`
	}
	err = tx.Exec(sqlStr, monthEndTime, prams).Error
	if err != nil {
		return err
	}
	tx.Commit()
	base.CHDB.Exec("system reload dictionary pas_olap_nj.DICT_INDI_PHJR_ZIPPER")
	return
}

//ShIndiPhjrEF 返回结构体
func ShIndiPhjrEF() base.EntityFunc {
	return func() interface{} {
		entity := ShIndiPhjr{}
		return &entity
	}
}

//ShIndiPhjrESF 返回结构体数组
func ShIndiPhjrESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []ShIndiPhjr
		return &entities
	}
}

func init() {
	base.SetAfterCallBack("ShIndiPhjr", ShIndiPhjrAfterImport)
	base.DaoPoolObj.Put("ShIndiPhjr", base.NewDefaultDao(ShIndiPhjrEF(), ShIndiPhjrESF(), nil, "my"))
}
